package com.hfy.pcberpbackend.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hfy.pcberpbackend.entity.Supplier;
import com.hfy.pcberpbackend.mapper.SupplierMapper;
import com.hfy.pcberpbackend.service.SupplierService;
import com.hfy.pcberpbackend.dto.SupplierQueryDTO;
import com.hfy.pcberpbackend.common.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.StrUtil;

import java.util.*;

/**
 * 供应商Service实现类
 */
@Slf4j
@Service
public class SupplierServiceImpl extends ServiceImpl<SupplierMapper, Supplier> implements SupplierService {
    
    @Override
    public PageResult<Supplier> getSupplierPage(SupplierQueryDTO query) {
        log.info("分页查询供应商列表，查询条件：{}", query);
        
        Page<Supplier> page = new Page<>(query.getPage(), query.getSize());
        IPage<Supplier> result = baseMapper.selectSupplierPage(page, query);
        
        return PageResult.of(result.getRecords(), result.getTotal(), 
                           result.getCurrent(), result.getSize());
    }
    
    @Override
    public Supplier getSupplierById(Long id) {
        log.info("根据ID获取供应商详情，ID：{}", id);
        
        Supplier supplier = getById(id);
        if (supplier == null) {
            throw new RuntimeException("供应商不存在");
        }
        return supplier;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createSupplier(Supplier supplier) {
        log.info("新增供应商：{}", supplier);
        
        // 检查供应商代码是否存在
        if (isSupplierCodeExists(supplier.getSupplierCode(), null)) {
            throw new RuntimeException("供应商代码已存在");
        }
        
        // 设置默认状态
        if (StrUtil.isBlank(supplier.getStatus())) {
            supplier.setStatus("active");
        }
        
        save(supplier);
        return supplier.getId();
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSupplier(Long id, Supplier supplier) {
        log.info("更新供应商信息，ID：{}，数据：{}", id, supplier);
        
        // 检查供应商是否存在
        Supplier existingSupplier = getSupplierById(id);
        
        // 检查供应商代码是否重复（排除自己）
        if (StrUtil.isNotBlank(supplier.getSupplierCode()) && 
            !supplier.getSupplierCode().equals(existingSupplier.getSupplierCode()) &&
            isSupplierCodeExists(supplier.getSupplierCode(), id)) {
            throw new RuntimeException("供应商代码已存在");
        }
        
        // 更新数据
        supplier.setId(id);
        updateById(supplier);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSupplier(Long id) {
        log.info("删除供应商，ID：{}", id);
        
        // 检查供应商是否存在
        getSupplierById(id);
        
        // 逻辑删除
        removeById(id);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDeleteSuppliers(List<Long> ids) {
        log.info("批量删除供应商，IDs：{}", ids);
        
        if (ids == null || ids.isEmpty()) {
            throw new RuntimeException("删除的ID列表不能为空");
        }
        
        // 批量逻辑删除
        removeByIds(ids);
    }
    
    @Override
    public List<Map<String, String>> getSupplierTypes() {
        List<Map<String, String>> types = new ArrayList<>();
        
        Map<String, String> material = new HashMap<>();
        material.put("value", "material");
        material.put("label", "原材料供应商");
        types.add(material);
        
        Map<String, String> equipment = new HashMap<>();
        equipment.put("value", "equipment");
        equipment.put("label", "设备供应商");
        types.add(equipment);
        
        Map<String, String> service = new HashMap<>();
        service.put("value", "service");
        service.put("label", "服务供应商");
        types.add(service);
        
        Map<String, String> other = new HashMap<>();
        other.put("value", "other");
        other.put("label", "其他");
        types.add(other);
        
        return types;
    }
    
    @Override
    public boolean isSupplierCodeExists(String supplierCode, Long excludeId) {
        if (StrUtil.isBlank(supplierCode)) {
            return false;
        }
        
        int count = baseMapper.countBySupplierCode(supplierCode, excludeId);
        return count > 0;
    }
} 